package org.jsets.fastboot.security.authc;

import java.util.Objects;
import org.jsets.fastboot.security.cache.Cache;
import org.jsets.fastboot.security.cache.ICacheManager;
import org.jsets.fastboot.security.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PasswdRetryWatcher {

	private final SecurityProperties properties;
	private final IPasswdRetryHandler passwdRetryHandler;
	private final Cache cache;
	private final Object cacheMonitor = new Object();

	public PasswdRetryWatcher(SecurityProperties properties, IPasswdRetryHandler passwdRetryHandler, ICacheManager cacheManager) {
		this.properties = properties;
		this.passwdRetryHandler = passwdRetryHandler;
		this.cache = cacheManager.create(properties.getPasswdRetryTimesCacheName());
		log.info("PasswdRetryWatcher初始化完成");
	}

	public int increase(String account) {
		int count = 0;
		if (null != this.passwdRetryHandler) {
			synchronized (cacheMonitor) {
				Object value = this.cache.get(account);
				if (Objects.isNull(value)) {
					count = new Integer(0);
					this.cache.put(account, ++count, properties.getPasswdRetryTimesCacheTimeout());
				} else {
					count = (Integer) value;
					this.cache.put(account, ++count);
				}
			}
		}
		return count;
	}

	public void cleanup(String account) {
		this.cache.delete(account);
	}

	public String onPasswdRetry(String username, int currentTimes) {
		if (null != this.passwdRetryHandler) {
			return this.passwdRetryHandler.onPasswdRetry(username, this.properties.getPasswordRetryMaximum(), currentTimes);
		}
		return null;
	}
}
